from django.contrib.auth.hashers import make_password
# django自带认证模块
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
# django自带认证模块
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.db.models import Q
from django.shortcuts import reverse
from django.views.generic import View, ListView, CreateView, UpdateView, DeleteView

User = get_user_model()


# class IndexView(View):
#     """
#     首页
#     """
#     def get(self, request):
#         print(request.user)
#         print(request.user.is_authenticated)
#         if not request.user.is_authenticated:
#             return HttpResponseRedirect(reverse("accounts:login"))
#         return render(request, 'index.html')

# class IndexView(View):
#     # login_url 用户没有通过跳转的地址，默认是 settings.LOGIN_URL
#     # @method_decorator(login_required(login_url="/accounts/login/"))
#     @method_decorator(login_required())
#     def get(self, request):
#         return render(request, 'index.html')

#     @method_decorator(login_required())
#     def post(self, request):
#         print("hello")
#         return render(request, 'index.html')


class IndexView(LoginRequiredMixin,PermissionRequiredMixin, View):
    """
    登录功能
    """
    # 用户没有通过时跳转的地址，默认是 settings.LOGIN_URL.
    login_url = '/accounts/login/'
    redirect_field_name = 'redirect_to'  
    # redirect_field_name = None         
    permission_required = ('auth.view_permission','auth.view_group')  

    def get(self, request):
        return render(request, 'index.html')

    def post(self, request):
        print("hello")
        return render(request, 'index.html')

class UserAddView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, CreateView):
    """
    添加用户
    """

    template_name = "users/form.html"
    model = User
    fields = ('username', 'name', 'phone','sex')
    permission_required = 'users.add_userprofile'
    success_message = '%(name)s 用户添加成功！'

    def get_success_url(self):
        if "_addanother" in self.request.POST:
            return reverse('users:add')
        return reverse('users:list')


    def form_valid(self, form):
        """
        用户默认密码为其用户名
        """
        password = form.cleaned_data['username']
        print(form.instance)  # user = UserProfile.objects.get(pk=1)
        form.instance.password = make_password(password)
        return super().form_valid(form)


class UserListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
    """
    用户列表
    """
    template_name = "users/list.html"
    model = User
    permission_required = 'users.view_userprofile'
    paginate_by = 5
    keyword = ""

    # 数据过滤
    def get_queryset(self):
        queryset = super(UserListView, self).get_queryset()
        queryset = queryset.exclude(username='admin')
        self.keyword = self.request.GET.get("keyword", "")
        if self.keyword:
            queryset = queryset.filter(Q(name__icontains=self.keyword) |
                                       Q(username__icontains=self.keyword) |
                                       Q(phone__icontains=self.keyword))

        return queryset

    # 搜索关键字传给前端
    def get_context_data(self, **kwargs):
        context = super(UserListView, self).get_context_data(**kwargs)
        context['keyword'] = self.keyword
        return context


class UserUpdateView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, UpdateView):
    """
    用户更新
    """
    template_name = "users/form.html"
    model = User
    fields = ('username', 'name', 'phone','sex',)
    permission_required = 'users.change_userprofile'
    success_message = '%(name)s 更新成功！'

    def get_success_url(self):
        if '_addanother' in self.request.POST:
            return reverse('users:add')
        elif '_savedit' in self.request.POST:
            return reverse('users:modify', kwargs={'pk': self.kwargs['pk']})
        else:
            return reverse('users:list')


class UserDelateView(LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
    """
    删除用户
    """
    template_name = 'users/user_confirm_delete.html'
    model = User
    permission_required = 'users.delete_userprofile'

    def get_success_url(self):
        return reverse('users:list')




from django.shortcuts import render

# Create your views here.
from elasticsearch import Elasticsearch
es = Elasticsearch(['121.36.78.226'], timeout=3600)
res = es.search(index="flow-*", filter_path=['hits.hits._source.date', 'hits.hits._source.content'],body={

  "size": 500,
  "query": {
    "bool": {
      "must": [
        {
          "exists": {
            "field": "content"
          }
        },
        {
          "exists": {
            "field": "date"
          }
        },
        {
          "range": {
            "@timestamp": {
              "format": "strict_date_optional_time",
              "gte": "now-8h",
              "lte": "now"
             # {'@timestamp':{'gte': end_time, 'lt':beg_time}}

            }
          }
        }
      ],
    }
  },
  "highlight": {


    "fields": {
      "*": {}
    },
  }
})
print(res)





